<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="0" :sm="2" :md="4" :lg="6"
        ><div class="grid-content bg-purple"></div
      ></el-col>
      <el-col :xs="24" :sm="20" :md="16" :lg="12">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>工时填报APP</span>
          </div>

          <el-form :model="headForm" label-width="80px">
            <el-row>
              <el-col :span="24" v-if="false">
                <el-form-item label="编号" prop="no">
                  <el-input
                    v-model="headForm.no"
                    placeholder="请输入编号"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="姓名" prop="name">
                  <el-input
                    v-model="headForm.name"
                    placeholder="请输入姓名"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="部门" prop="dept">
                  <el-input
                    v-model="headForm.dept"
                    placeholder="请输入部门"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="填报日期" prop="date">
                  <el-date-picker
                    v-model="headForm.date"
                    type="date"
                    placeholder="请输入填报日期"
                    style="width: 100%"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-divider style="margin: 12px 0" />

            <div style="padding: 0px 0px 15px">
              <span>今天已填报记录</span>
            </div>
            <el-row>
              <el-col :span="24">
                <el-table :data="initData" style="width: 100%">
                  <el-table-column
                    prop="number"
                    label="序号"
                    type="index"
                    width="80"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <span>{{ (scope.row.number = scope.$index + 1) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="projectCode"
                    label="项目代码"
                    width="120"
                  />
                  <el-table-column
                    prop="stageName"
                    label="开发阶段"
                    width="120"
                  />
                  <el-table-column prop="officeName" label="事务种类" />
                  <el-table-column
                    label="申报日期"
                    prop="workTime"
                    align="center"
                    width="180"
                  >
                    <template slot-scope="scope">
                      <span>{{ parseTime(scope.row.workTime) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="workHour"
                    label="工时(H)"
                    align="center"
                    width="80"
                  />
                  <el-table-column
                    prop="workRemark"
                    label="备注"
                    show-overflow-tooltip
                  />
                </el-table>
              </el-col>
            </el-row>
            <el-divider style="margin: 12px 0" />

            <el-row :gutter="10" class="mb8">
              <el-col :span="12">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  style="width: 100%"
                  >添加行</el-button
                >
              </el-col>
              <el-col :span="12">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  @click="handleDelete"
                  style="width: 100%"
                  >删除行</el-button
                >
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-table
                  :data="tableData"
                  style="width: 100%"
                  @selection-change="handleSelectionChange"
                  @row-click="handleUpdate"
                >
                  <el-table-column type="selection" width="50" align="center" />
                  <el-table-column
                    prop="number"
                    label="序号"
                    type="index"
                    width="50"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <span>{{ (scope.row.number = scope.$index + 1) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="projectCode"
                    label="项目代码"
                    width="80"
                    align="center"
                  />
                  <el-table-column
                    prop="stageName"
                    label="开发阶段"
                    width="80"
                    align="center"
                  />
                  <el-table-column
                    prop="officeName"
                    label="事务种类"
                    width="120"
                  />
                  <el-table-column
                    prop="workHour"
                    label="工时(H)"
                    align="center"
                    width="70"
                  />
                  <el-table-column
                    prop="workRemark"
                    label="备注"
                    show-overflow-tooltip
                  />
                </el-table>
              </el-col>
            </el-row>

            <el-row :gutter="10" class="mt50 mb8">
              <el-col :span="24">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-check"
                  size="mini"
                  @click="handleSave"
                  style="width: 100%"
                  >提交</el-button
                >
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-col>
      <el-col :xs="0" :sm="2" :md="4" :lg="6"
        ><div class="grid-content bg-purple"></div>
      </el-col>
    </el-row>

    <!-- 新增、修改 弹框 -->
    <el-dialog
      title="工时填报"
      :visible.sync="open"
      v-if="open"
      width="80%"
      append-to-body
    >
      <el-form
        ref="detailForm"
        :model="detailForm"
        :rules="rules"
        label-position="top"
        label-width="120px"
      >
        <el-form-item label="项目代码" prop="projectId">
          <el-select
            v-model="detailForm.projectId"
            placeholder="请输入项目代码"
            clearable
            filterable
            style="width: 100%"
            @change="changeProject"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.projectId"
              :label="item.projectCode"
              :value="item.projectId"
              :hidden="item.status == 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目开发阶段" prop="stageName">
          <el-input
            v-model="detailForm.stageName"
            placeholder="请输入当前项目开发阶段"
            disabled
          />
        </el-form-item>
        <el-form-item label="事务类型" prop="officeId">
          <el-select
            v-model="detailForm.officeId"
            placeholder="请输入事务类型"
            clearable
            filterable
            style="width: 100%"
            @change="changeOffice"
          >
            <el-option
              v-for="item in officeOptions"
              :key="item.officeId"
              :label="item.officeName"
              :value="item.officeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工时(H)" prop="workHour">
          <el-input-number
            v-model="detailForm.workHour"
            :min="0.5"
            :max="24"
            :step="0.5"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注" prop="workRemark">
          <el-input
            v-model="detailForm.workRemark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { init, fillSave, delToken } from '@/api/work/fill'
import { optionSelect as getProjects } from '@/api/work/project'
import { optionSelect as getOffices } from '@/api/work/office'
import { setToken, getToken, removeToken } from '@/utils/auth'
import axios from 'axios'

export default {
  name: 'WorkApp',
  data() {
    return {
      // 选中数组
      ids: [],
      // 是否显示弹出层
      open: false,
      // 表格数据
      tableData: [],
      // 头表单
      headForm: {},
      // 初始化今天已填报数据
      initData: [],
      // 填报明细表单
      detailForm: {},
      // 项目选项
      projectOptions: [],
      // 所有事务类型选项
      allOfficeOptions: [],
      // 事务类型选项
      officeOptions: [],
      // 开始时间
      startTime: new Date(),
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: '项目不能为空', trigger: 'change' }
        ],
        officeId: [
          { required: true, message: '事务种类不能为空', trigger: 'change' }
        ],
        workHour: [
          { required: true, message: '工时不能为空', trigger: 'blur' }
        ],
        workRemark: [
          { required: true, message: '备注不能为空', trigger: 'blur' }
        ]
      },
      // Token
      token: ''
    }
  },
  created() {
    this.init()
  },
  methods: {
    // APP退出
    clearToken() {
      // debugger
      delToken().then((response) => {
        removeToken()
      })
    },
    /** 初始化表单 */
    init() {
      let userId = undefined
      let username = undefined
      let nickname = undefined
      let dept = undefined
      let token = undefined
      /** 判断路由，防止获取不到路由参数，路由重定向到 index */
      if (this.$route && this.$route.query) {
        userId = this.$route.query.userid
        username = this.parseStrEmpty(this.$route.query.username)
        /** 解码 */
        nickname = this.parseStrEmpty(
          decodeURIComponent(this.$route.query.nickname)
        )
        dept = this.parseStrEmpty(decodeURIComponent(this.$route.query.dept))
        /** 获取token */
        token = this.$route.query.token
        setToken(token)
        this.$store.commit('SET_TOKEN', token)

        // 初始化当天已填数据
        this.token = token
        this.initNowDateTable(token)
      }
      /** 头表单 */
      this.headForm = {
        userId: userId,
        no: username,
        name: nickname,
        dept: dept,
        date: new Date()
      }
    },
    /** 初始化当天已填数据 */
    initNowDateTable(token) {
      axios({
        url: process.env.VUE_APP_BASE_API + '/work/fill/init',
        method: 'get',
        headers: { Authorization: 'Bearer ' + token }
      }).then((response) => {
        this.initData = response.data.data
      })
      // init().then((response) => {
      //   this.initData = response.data
      // })
      // debugger
    },
    /** 重置填报表单 */
    resetDetailForm() {
      this.detailForm = {
        projectId: '',
        projectCode: '',
        stageId: '',
        stageName: '',
        officeId: '',
        officeName: '',
        workHour: 0,
        workRemark: ''
      }
    },
    /** 添加行操作 */
    handleAdd() {
      this.resetDetailForm()
      this.getProjects()
      this.getOffices()
      this.open = true
    },
    /** 修改按钮操作 */
    handleUpdate(row, event, column) {
      this.resetDetailForm()
      let copy = Object.assign({}, row) //row是所编辑本行内数据对象
      this.detailForm = copy
      this.getProjects()
      this.getOffices()
      this.open = true
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.number)
    },
    /** 删除行操作 */
    handleDelete() {
      if (this.ids && this.ids.length > 0) {
        this.ids.forEach((number) => {
          this.tableData.splice(number - 1, this.ids.length)
        })
      } else {
        this.$message.error('提示：请选择需要删除的行信息')
      }
    },
    /** 初始化项目下拉 */
    getProjects() {
      getProjects().then((response) => {
        this.projectOptions = response.data
      })
    },
    /** 初始化事务种类下拉 */
    getOffices() {
      getOffices().then((response) => {
        this.allOfficeOptions = response.data
      })
    },
    /** 选择项目，带出开发阶段 */
    changeProject(data) {
      let offices = this.allOfficeOptions
      if (data) {
        let option = this.projectOptions.find((i) => i.projectId == data)
        this.detailForm.projectCode = option.projectCode
        this.detailForm.stageId = option.stageId
        this.detailForm.stageName = option.stageName
        // Other阶段，不对应项目代码
        if (option.stageName === 'Other') {
          this.officeOptions = offices.filter((e) => e.officeId != 1)
        } else {
          // 其他开发阶段，对应项目代码
          this.officeOptions = offices.filter((e) => e.officeId === 1)
        }
      } else {
        this.detailForm.projectId = ''
        this.detailForm.projectCode = ''
        this.detailForm.stageId = ''
        this.detailForm.stageName = ''
        this.detailForm.officeId = ''
        this.detailForm.officeName = ''
        this.officeOptions = []
      }
    },
    /** 选择事务种类 */
    changeOffice(data) {
      if (data) {
        let option = this.officeOptions.find((i) => i.officeId == data)
        this.detailForm.officeId = option.officeId
        this.detailForm.officeName = option.officeName
      } else {
        this.detailForm.officeId = undefined
        this.detailForm.officeName = undefined
      }
    },
    /** 取消按钮 */
    cancel() {
      this.resetDetailForm()
      this.open = false
    },
    /** 验证 每天时间总和不超过24小时 */
    verifyTime(data) {
      let flag = false
      let sum = 0
      let arrquantitynew = this.tableData
        .filter((e) => e.number != data.number)
        .map((item) => {
          return item.workHour
        })
      if (arrquantitynew && arrquantitynew.length > 0) {
        sum = arrquantitynew.reduce((x, y) => x + y)
      }
      if (sum + data.workHour > 24) {
        flag = true
      }
      return flag
    },
    /** 填报明细提交按钮 */
    submitForm() {
      this.$refs['detailForm'].validate((valid) => {
        if (valid) {
          const detailInfo = this.detailForm
          /** 验证 */
          if (this.verifyTime(this.detailForm)) {
            /** 填报工时总和不能超过24小时 */
            this.$message.warning(
              '提示：日期 ' +
                this.parseTime(this.headForm.date, '{y}-{m}-{d}') +
                ' 填报工时 总和 不能超过24小时'
            )
          } else {
            /** 保存 */
            if (detailInfo.number) {
              this.tableData = this.tableData.map((item) =>
                item.number === detailInfo.number ? detailInfo : item
              )
            } else {
              this.tableData.push(detailInfo)
            }
            this.open = false
          }
        }
      })
    },
    /** 提交按钮 */
    handleSave() {
      if (!this.headForm.date) {
        this.$message.error('提示：请填写填报时间')
      } else {
        if (this.tableData && this.tableData.length > 0) {
          this.tableData.forEach(
            (detail) => (detail.workTime = this.headForm.date)
          )
          const saveFrom = {
            userId: this.headForm.userId,
            fillTime: this.headForm.date,
            fillStartTime: this.startTime,
            fillEndTime: new Date(),
            fillDetails: this.tableData
          }
          fillSave(saveFrom).then((response) => {
            this.$modal.msgSuccess(response.msg)
            this.tableData.splice(0, this.tableData.length)

            // 初始化当天已填数据
            this.initNowDateTable(this.token)
          })
        } else {
          this.$message.warning('提示：请填报工时信息')
        }
      }
    }
  }
}
</script>
<style>
.bg-purple {
  background: white;
}
.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>
